<?php
class AuthController extends Zend_Controller_Action
{
	public function init() {
		$this->view->addHelperPath(
		'ZendX/JQuery/View/Helper', 
		'ZendX_JQuery_View_Helper');
	}

	public function loginAction()
	{
		$db = $this->_getParam('db');

		$loginform = new Application_Form_Login();

		if ($loginform->isValid($_POST)){

			$adapter = new Zend_Auth_Adapter_DbTable($db,'users','username','password');

			$adapter->setIdentity($loginform->getValue('username'));
			$adapter->setCredential($loginform->getValue('password'));

			$auth=Zend_Auth::getInstance();
			$result= $auth->authenticate($adapter);
				

			if ($result->isValid()) {
				$this->_helper->FlashMessenger('Successful login');
				$storage = Zend_Auth::getInstance()->getStorage();
				$storage->write($adapter->getResultRowObject(null,'password'));
				if ($auth->getIdentity()->role == 'admin'){
					$this->_helper->redirector('manage','index');
				}
				

			}
			else{
				$loginform->getElement('username')->addError('Utilisateur inconnu');
				
			}
		}
		$this->view->form = $loginform;

	}

	public function logoutAction()
	{
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		$this->_redirect('/');
	}

	public function preDispatch() {
		if (Zend_Auth::getInstance ()->hasIdentity ()) {
			if ('logout' != $this->getRequest ()->getActionName ()) {
				$this->_helper->redirector ( 'index', 'index' );
			}
		} else {
			if ('logout' == $this->getRequest ()->getActionName ()) {
				$this->_helper->redirector ( 'index' );
			}
		}
	}
}
